﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using OfficeOpenXml;

namespace TYAJZWeb.Utils
{
    class ExcelExporter
    {
        public static void Export<T>(String path, IList<T> models)
        {
            if (System.IO.File.Exists(path)) System.IO.File.Delete(path);

            Dictionary<int, PropertyInfo> properties = new Dictionary<int, PropertyInfo>();
            foreach (var t in typeof(T).GetProperties())
            {
                var attrs = t.GetCustomAttributes(typeof(DisplayAttribute), true) as DisplayAttribute[];
                if (attrs.Length > 0)
                {
                    properties.Add(attrs[0].Order, t);
                }
            }

            List<PropertyInfo> infos = properties.OrderBy(t => t.Key).Select(t => t.Value).ToList();

            String[] characters = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

            using (ExcelPackage excelHandler = new ExcelPackage(new System.IO.FileInfo(path)))
            {
                var sheet = excelHandler.Workbook.Worksheets.Add("过期设备");
                sheet.InsertRow(0, models.Count() + 1);
                for (int i = 0; i < infos.Count(); i++)
                {
                    var attrs = infos[i].GetCustomAttributes(typeof(DisplayAttribute), true) as DisplayAttribute[];
                    sheet.SetValue(String.Format("{0}1", characters[i]), attrs[0].Name);
                }
                for (int i = 0; i < models.Count(); i++)
                {
                    for (int j = 0; j < infos.Count(); j++)
                    {
                        sheet.SetValue(String.Format("{0}{1}", characters[j], i + 2), infos[j].GetValue(models[i], null));
                    }
                }
                excelHandler.Save();
            }
        }
    }

}